热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

接受者|本文_SpringBoot2.x实践记:Mail

篇首语:本文由编程笔记#小编为大家整理,主要介绍了SpringBoot2.x实践记:Mail相关的知识,希望对你有一定的参考价值。目录

篇首语:本文由编程笔记#小编为大家整理,主要介绍了Spring Boot 2.x 实践记:Mail相关的知识,希望对你有一定的参考价值。



目录
  1. Maven 依赖
  2. SMTP配置
  3. 发送简单邮件
  4. 发送带附件邮件
  5. 发送html格式邮件
  6. 实战
  7. 测试
  8. 小结

TL;DR

本文是实践如何在Spring Boot 2中使用JavaMailSender发送邮件:


  • 发送简单邮件
  • 发送带附件邮件
  • 发送HTML格式邮件

1. Maven 依赖

<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-mailartifactId>
<version>2.2.6.RELEASEversion>
dependency>

2. SMTP配置

2.1. QQ邮箱

spring.mail.host&#61;smtp.exmail.qq.com
spring.mail.username&#61;xxx&#64;xxx.com
spring.mail.password&#61;xxxxxx
spring.mail.properties.mail.smtp.auth&#61;true
# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable&#61;true
spring.mail.properties.mail.smtp.starttls.required&#61;true

2.2. gmail

spring.mail.host&#61;smtp.gmail.com
spring.mail.port&#61;25
spring.mail.username&#61;xxx&#64;gmail.com
spring.mail.password&#61;xxxxxx
spring.mail.properties.mail.smtp.auth&#61;true
spring.mail.properties.mail.smtp.connectiontimeout&#61;5000
spring.mail.properties.mail.smtp.timeout&#61;5000
spring.mail.properties.mail.smtp.writetimeout&#61;5000

# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable&#61;true
spring.mail.properties.mail.smtp.starttls.required&#61;true

2.3. outlook

如果是内部服务器&#xff0c;需要由管理员提供基础信息。

spring.mail.host&#61;smtp-mail.outlook.com
spring.mail.port&#61;587
spring.mail.username&#61;xxx&#64;outlook.com
spring.mail.password&#61;xxxxxx

spring.mail.properties.mail.protocol&#61;smtp
spring.mail.properties.mail.tls&#61;true

spring.mail.properties.mail.smtp.auth&#61;true
spring.mail.properties.mail.smtp.starttls.enable&#61;true
spring.mail.properties.mail.smtp.ssl.trust&#61;smtp-mail.outlook.com

3. 发送简单邮件

&#64;Resource
private JavaMailSender mailSender;
public void sendSimpleMail()
SimpleMailMessage message &#61; new SimpleMailMessage();

message.setFrom("xxx&#64;xxx.com");
message.setTo("xxx&#64;xxx.com");
message.setSubject("主题&#xff1a;简单邮件");
message.setText("这是一封简单邮件");

try
mailSender.send(message);
catch (Exception e)
e.printStackTrace();



4. 发送带附件邮件

&#64;Resource
private JavaMailSender mailSender;
public void sendAttachmentsMail()
MimeMessage mimeMessage &#61; mailSender.createMimeMessage();

try
MimeMessageHelper helper &#61; new MimeMessageHelper(mimeMessage, true);
helper.setFrom("xxx&#64;xxx.com");
helper.setTo("xxx&#64;xxx.com");
helper.setSubject("主题&#xff1a;带有附件的邮件");
helper.setText("有附件");
FileSystemResource file &#61; new FileSystemResource(new File("/data/test.xlsx"));
helper.addAttachment("test.xlsx", file);

mailSender.send(mimeMessage);
catch (Exception e)
e.printStackTrace();



5. 发送HTML格式邮件

&#64;Resource
private JavaMailSender mailSender;
public Boolean sendHtmlMail()
MimeMessage mimeMessage &#61; mailSender.createMimeMessage();
try
MimeMessageHelper helper &#61; new MimeMessageHelper(mimeMessage, true);
helper.setFrom("xxx&#64;xxx.com");
helper.setTo("xxx&#64;xxx.com");
helper.setSubject("主题&#xff1a;带有html的邮件");
helper.setText("", true);
FileSystemResource file &#61; new FileSystemResource(new File("/web/test.jpg"));
helper.addInline("test.jpg", file);

mailSender.send(mimeMessage);
catch (Exception e)
e.printStackTrace();



6. 实战

  • github实战代码地址&#xff1a;

在实际邮件发送中&#xff0c;发送者通常为1个&#xff0c;而接受者通常是多个&#xff0c;而且还有抄送或密送&#xff0c;下面我们就来基于上面邮件发送的基本实现&#xff0c;来扩展实战一下。


6.1. 创建Spring Boot 启动类

package com.mickjoust.demo.springboot2_in_action.mail;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* &#64;author mickjoust
**/

&#64;SpringBootApplication
public class AppStartMail
public static void main(String[] args)
SpringApplication.run(AppStartMail.class,args);



6.2. 创建邮件对象

为了方便模拟传参数&#xff0c;我们创建一个简单的邮件对象。

package com.mickjoust.demo.springboot2_in_action.mail;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* &#64;author mickjoust
**/

&#64;Data
&#64;AllArgsConstructor
&#64;NoArgsConstructor
public class MailInfo
private String subject;
private String content;
private String from;
private String[] to;
private String[] cc;
private String[] bcc;
private String fileName;
private String filePath;


6.3. 创建Restful API

分别提供三个接口&#xff0c;接受发送邮件&#xff0c;如果发送成功则返回成功&#xff0c;否则返回失败。

package com.mickjoust.demo.springboot2_in_action.mail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import javax.annotation.Resource;
/**
* &#64;author mickjoust
**/

&#64;Slf4j
&#64;RestController
public class TestSendMailController
&#64;Resource
private SendMailService sendMailService;
&#64;PostMapping("/mail/simple")
public String sendSimpleMail(&#64;RequestBody MailInfo mailInfo)
if (sendMailService.sendSimpleMail(mailInfo))
return "true";

return "false";

&#64;PostMapping("/mail/attachment")
public String sendAttachmentsMail(&#64;RequestBody MailInfo mailInfo)
if (sendMailService.sendAttachmentsMail(mailInfo))
return "true";

return "false";

&#64;PostMapping("/mail/html")
public String sendHtmlMail(&#64;RequestBody MailInfo mailInfo)
if (sendMailService.sendHtmlMail(mailInfo))
return "true";

return "false";



6.4. 实现邮件发送服务

package com.mickjoust.demo.springboot2_in_action.mail;
/**
* &#64;author mickjoust
**/

public interface SendMailService
Boolean sendSimpleMail(MailInfo mailInfo);
Boolean sendAttachmentsMail(MailInfo mailInfo);
Boolean sendHtmlMail(MailInfo mailInfo);

package com.mickjoust.demo.springboot2_in_action.mail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
/**
* &#64;author mickjoust
**/

&#64;Slf4j
&#64;Service("sendMailService")
public class SendMailServiceImpl implements SendMailService
&#64;Resource
private JavaMailSender mailSender;
private boolean isEmpty(final String[] array)
return array &#61;&#61; null || array.length &#61;&#61; 0;

private boolean isNotEmpty(final String[] array)
return !isEmpty(array);

/**
* 发送普通邮件
* &#64;param subject 主题
* &#64;param content 内容
* &#64;param from 发自
* &#64;param to 发送
* &#64;param cc 抄送
* &#64;param bcc 密送
* &#64;return 返回
*/

public Boolean sendSimpleMail(String subject, String content, String from, String[] to,String[] cc,String[] bcc)
SimpleMailMessage message &#61; new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
if (isNotEmpty(cc))
message.setCc(cc);

if (isNotEmpty(bcc))
message.setBcc(bcc);

message.setSubject(subject);
message.setText(content);
try
mailSender.send(message);
return true;
catch (Exception e)
log.error("&#61;&#61;&#61;发送邮件异常",e);

return false;

/**
* 发送附件邮件
* &#64;param subject
* &#64;param content
* &#64;param from
* &#64;param fillepath /web/test.xlsx
* &#64;param filename test.xlsx
* &#64;param to
* &#64;param cc
* &#64;param bcc
* &#64;return
*/

public Boolean sendAttachmentsMail(String subject,String content,String from, String fillepath, String filename,
String[] to,
String[] cc,
String[] bcc)
MimeMessage mimeMessage &#61; mailSender.createMimeMessage();
try
MimeMessageHelper helper &#61; new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo(to);
if (isNotEmpty(cc))
helper.setCc(cc);

if (isNotEmpty(bcc))
helper.setBcc(bcc);

helper.setSubject(subject);
helper.setText(content);
FileSystemResource file &#61; new FileSystemResource(new File(fillepath));
helper.addAttachment(filename, file);
catch (Exception e)
e.printStackTrace();
log.error("&#61;&#61;&#61;创建附件邮件异常", e);

try
mailSender.send(mimeMessage);
return true;
catch (Exception e)
log.error("&#61;&#61;&#61;发送邮件异常",e);

return false;

/**
* 发送富文本邮件
* &#64;param subject
* &#64;param content 比如&#xff1a;
* &#64;param from
* &#64;param fillepath 比如&#xff1a;/web/test.jpg
* &#64;param filename 比如&#xff0c;test
* &#64;param to
* &#64;param cc
* &#64;param bcc
* &#64;return
*/

public Boolean sendHtmlMail(String subject,String content,String from, String fillepath, String filename,
String[] to,
String[] cc,
String[] bcc)
MimeMessage mimeMessage &#61; mailSender.createMimeMessage();
try
MimeMessageHelper helper &#61; new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo(to);
if (isNotEmpty(cc))
helper.setCc(cc);

if (isNotEmpty(bcc))
helper.setBcc(bcc);

helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file &#61; new FileSystemResource(new File(fillepath));
helper.addInline(filename, file);
catch (Exception e)
log.error("&#61;&#61;&#61;创建富文本邮件异常", e);

try
mailSender.send(mimeMessage);
return true;
catch (Exception e)
log.error("&#61;&#61;&#61;发送邮件异常",e);

return false;

&#64;Override
public Boolean sendSimpleMail(MailInfo mailInfo)
return sendSimpleMail(mailInfo.getSubject(),mailInfo.getContent(),mailInfo.getFrom(),
mailInfo.getTo(),mailInfo.getCc(),mailInfo.getBcc());

&#64;Override
public Boolean sendAttachmentsMail(MailInfo mailInfo)
return sendAttachmentsMail(mailInfo.getSubject(),mailInfo.getContent(),mailInfo.getFrom(),
mailInfo.getFilePath(),mailInfo.getFileName(),mailInfo.getTo(),mailInfo.getCc(),mailInfo.getBcc());

&#64;Override
public Boolean sendHtmlMail(MailInfo mailInfo)
return sendHtmlMail(mailInfo.getSubject(),mailInfo.getContent(),mailInfo.getFrom(),
mailInfo.getFilePath(),mailInfo.getFileName(),mailInfo.getTo(),mailInfo.getCc(),mailInfo.getBcc());



7. 测试


8. 小结

到此&#xff0c;我们就学会了在Spring Boot 2 中发送邮件的方法。


推荐阅读
  • 本文介绍了多因子选股模型在实际中的构建步骤,包括风险源分析、因子筛选和体系构建,并进行了模拟实证回测。在风险源分析中,从宏观、行业、公司和特殊因素四个角度分析了影响资产价格的因素。具体包括宏观经济运行和宏经济政策对证券市场的影响,以及行业类型、行业生命周期和行业政策对股票价格的影响。 ... [详细]
  • 1、概述首先和大家一起回顾一下Java消息服务,在我之前的博客《Java消息队列-JMS概述》中,我为大家分析了:然后在另一篇博客《Java消息队列-ActiveMq实战》中 ... [详细]
  • 基于PgpoolII的PostgreSQL集群安装与配置教程
    本文介绍了基于PgpoolII的PostgreSQL集群的安装与配置教程。Pgpool-II是一个位于PostgreSQL服务器和PostgreSQL数据库客户端之间的中间件,提供了连接池、复制、负载均衡、缓存、看门狗、限制链接等功能,可以用于搭建高可用的PostgreSQL集群。文章详细介绍了通过yum安装Pgpool-II的步骤,并提供了相关的官方参考地址。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 关于我们EMQ是一家全球领先的开源物联网基础设施软件供应商,服务新产业周期的IoT&5G、边缘计算与云计算市场,交付全球领先的开源物联网消息服务器和流处理数据 ... [详细]
  • 标题: ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • 本文介绍了使用Spark实现低配版高斯朴素贝叶斯模型的原因和原理。随着数据量的增大,单机上运行高斯朴素贝叶斯模型会变得很慢,因此考虑使用Spark来加速运行。然而,Spark的MLlib并没有实现高斯朴素贝叶斯模型,因此需要自己动手实现。文章还介绍了朴素贝叶斯的原理和公式,并对具有多个特征和类别的模型进行了讨论。最后,作者总结了实现低配版高斯朴素贝叶斯模型的步骤。 ... [详细]
  • 本文介绍了解决java开源项目apache commons email简单使用报错的方法,包括使用正确的JAR包和正确的代码配置,以及相关参数的设置。详细介绍了如何使用apache commons email发送邮件。 ... [详细]
  • 精讲代理设计模式
    代理设计模式为其他对象提供一种代理以控制对这个对象的访问。代理模式实现原理代理模式主要包含三个角色,即抽象主题角色(Subject)、委托类角色(被代理角色ÿ ... [详细]
  •  项目地址https:github.comffmydreamWiCar界面做的很难看,美工方面实在不在行。重点是按钮触摸事件的处理,这里搬了RepeatListener项目代码,例 ... [详细]
  • pc电脑如何投屏到电视?DLNA主要步骤通过DLNA连接,使用WindowsMediaPlayer的流媒体播放举例:电脑和电视机都是连接的 ... [详细]
  • docker安装到基本使用
    记录docker概念,安装及入门日常使用Docker安装查看官方文档,在&quot;Debian上安装Docker&quot;,其他平台在&quot;这里查 ... [详细]
author-avatar
mobiledu2502913165
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有